package com.fy.auth.controller;

import com.alibaba.fastjson.JSON;
import com.fy.auth.feign.UserFeignService;
import com.fy.common.util.HttpUtils;
import com.fy.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * 功能描述: 第三方登录
 * 〈〉
 *
 * @author : fuyi
 * @date : 2022-06-11 14:05
 */
@Slf4j
@RestController
public class OAuth2Controller {

    @Autowired
    private UserFeignService userFeignService;

    /**
     * 功能描述:
     * 用户访问路径https://api.weibo.com/oauth2/authorize?client_id=4107805231&response_type=code&redirect_uri=http://localhost:8089/oauth2.0/weibo/success
     *
     * @return : java.lang.String
     * @author : fuyi
     * @date : 2022-06-10 16:55
     */
    @GetMapping(value = "/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

        Map<String, String> map = new HashMap<>();
        map.put("client_id", "4107805231");
        map.put("client_secret", "bce1d565651663c66618fbbde122ff29");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://localhost:8089/oauth2.0/weibo/success");
        map.put("code", code);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
        //2、处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了access_token,转为通用社交登录对象
            String json = EntityUtils.toString(response.getEntity());

            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道了哪个社交用户
            //1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个用户信息，以后这个社交账号就对应指定的用户）
            //登录或者注册这个社交用户
            System.out.println(socialUser.getAccess_token());
            System.out.println(socialUser.getUid());
            //调用远程服务
            Map<String, String> stringStringMap = userFeignService.oauthLogin(socialUser);
            if (true) {
                //2、登录成功跳回首页
                return "登陆成功";
            } else {
                return "登录失败";
            }
        } else {
            return "失败";
        }
    }
}
